Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace OliverHine.DNN.Weather

    Public MustInherit Class WeatherModule
        Inherits Entities.Modules.PortalModuleBase
        Implements Entities.Modules.IPortable

#Region "Controls"
        Protected WithEvents w As OliverHine.Weather.Weather
        Protected WithEvents s As OliverHine.Weather.Search
#End Region

        Private Sub BuildWeatherControl()

            If Settings.Contains("WeatherStation") Then
                w.WeatherLocation = GetCookie("WeatherLocation", Settings("WeatherStation").ToString())
            End If

            If Settings.Contains("ExtForecastLength") AndAlso Microsoft.VisualBasic.IsNumeric(Settings("ExtForecastLength").ToString) Then
                w.WeatherLength = Integer.Parse(Settings("ExtForecastLength").ToString)
            End If

            If Settings.Contains("PerUser") AndAlso CType(Settings("PerUser"), Boolean) = True Then
                If Not UserInfo Is Nothing AndAlso UserId > -1 Then
                    If DotNetNuke.Common.Utilities.Null.IsNull(UserInfo.Profile.PostalCode) = False Then
                        w.WeatherLocation = Me.UserInfo.Profile.PostalCode

                        'TODO, auto lookup users zip, and check if location exists, if not display default
                    End If
                End If
            End If

            If Settings.Contains("Unit") Then
                Select Case Settings("Unit").ToString.ToLower()
                    Case "f"
                        w.WeatherUnit = OliverHine.Weather.Common.Enums.Unit.Fahrenheit
                    Case "c"
                        w.WeatherUnit = OliverHine.Weather.Common.Enums.Unit.Celsius
                End Select
            End If

            If Settings.Contains("UserInput") AndAlso CType(Settings("UserInput"), Boolean) = True Then
                s.Visible = True
            Else
                s.Visible = False
            End If

            If (Settings.Contains("SeparateForecast") AndAlso Boolean.Parse(Settings("SeparateForecast").ToString) = True) AndAlso Settings.Contains("SeparateOptions") Then
                Select Case Settings("SeparateOptions").ToString.ToLower
                    Case "b"
                        w.WeatherStyle = OliverHine.Weather.Common.Enums.Style.TodayWithExtended
                    Case "e"
                        w.WeatherStyle = OliverHine.Weather.Common.Enums.Style.OnlyExtended
                    Case "t"
                        w.WeatherStyle = OliverHine.Weather.Common.Enums.Style.OnlyToday
                    Case Else
                        w.WeatherStyle = OliverHine.Weather.Common.Enums.Style.Today
                End Select
                Trace.Warn(ModuleId & " " & Settings("SeparateOptions").ToString.ToLower)
            End If

            If Settings.Contains("DetailedToday") Then
                w.WeatherTodayDetails = Boolean.Parse(Settings("DetailedToday").ToString)
            End If

            If Settings.Contains("DisplayLocation") Then
                Select Case Settings("DisplayLocation").ToString.ToLower
                    Case "dnam"
                        w.Title = OliverHine.Weather.Common.Enums.Title.Closest
                    Case "obst"
                        w.Title = OliverHine.Weather.Common.Enums.Title.Actual
                    Case "none"
                        w.Title = OliverHine.Weather.Common.Enums.Title.Hide
                End Select
            End If

            If Settings.Contains("IconLarge") Then
                w.IconSizeLarge = Settings("IconLarge").ToString()
            End If

            If Settings.Contains("IconSmall") Then
                w.IconSizeSmall = Settings("IconSmall").ToString()
            End If
        End Sub

#Region "Event Handlers"
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try

                BuildWeatherControl()

            Catch exc As Exception
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        Private Sub s_FoundLocation(ByVal LocationId As String) Handles s.FoundLocation

            w.WeatherLocation = LocationId

            SetCookie("WeatherLocation", LocationId)
        End Sub
#End Region

        Private Sub SetCookie(ByVal Key As String, ByVal Value As String)
            Dim sCacheKey As String = String.Format("{0}:{1}", Me.ID, Key)

            If Request.IsAuthenticated Then
                'user is authenticated
                Me.UserInfo.Profile.SetProfileProperty(sCacheKey, Value)

            Else
                If Context.Request.Browser.Cookies = True Then
                    If Not Context.Request.Cookies(sCacheKey) Is Nothing Then
                        Context.Response.Cookies.Remove(sCacheKey)

                        Context.Response.Cookies(sCacheKey).Value = Value
                    Else
                        Context.Response.Cookies(sCacheKey).Value = Value
                    End If
                End If
            End If
        End Sub
        Private Function GetCookie(ByVal Key As String, ByVal DefaultValue As String) As String
            Dim sCacheKey As String = String.Format("{0}:{1}", Me.ID, Key)

            If Request.IsAuthenticated Then
                Dim objProfileValue As String = Me.UserInfo.Profile.GetPropertyValue(CacheKey)
                If objProfileValue.Length = 0 Then
                    Return DefaultValue
                Else
                    Return objProfileValue
                End If
            End If
            If Context.Request.Browser.Cookies = True Then
                If Not Context.Request.Cookies(sCacheKey) Is Nothing Then
                    Return Context.Request.Cookies(sCacheKey).Value
                Else
                    Return DefaultValue
                End If
            End If
        End Function

#Region "Optional Interfaces"
        Public Function ExportModule(ByVal ModuleID As Integer) As String Implements Entities.Modules.IPortable.ExportModule
            ' included as a stub only so that the core knows this module Implements Entities.Modules.IPortable
        End Function

        Public Sub ImportModule(ByVal ModuleID As Integer, ByVal Content As String, ByVal Version As String, ByVal UserID As Integer) Implements Entities.Modules.IPortable.ImportModule
            ' included as a stub only so that the core knows this module Implements Entities.Modules.IPortable
        End Sub
#End Region

#Region " Web Form Designer Generated Code "

        'This call is required by the Web Form Designer.
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

        End Sub

        'NOTE: The following placeholder declaration is required by the Web Form Designer.
        'Do not delete or move it.
        Private designerPlaceholderDeclaration As System.Object

        Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
            'CODEGEN: This method call is required by the Web Form Designer
            'Do not modify it using the code editor.
            InitializeComponent()

            w.UniqueIdentifier = ModuleId.ToString

            Dim userLanguage As String = PortalSettings.DefaultLanguage

            userLanguage = Globalization.CultureInfo.CurrentCulture.ToString
            
            If Request.IsAuthenticated = True Then
                If Null.IsNull(UserInfo.Profile.PreferredLocale) = False Then
                    userLanguage = UserInfo.Profile.PreferredLocale
                End If
            End If




            w.WeatherLanguage = userLanguage
            s.WeatherLanguage = userLanguage

            If Request.QueryString("debugweatherlang") IsNot Nothing Then
                Response.Write(String.Format("CurrentCulture:{0}<br/>PreferredLocale:{1}<br/>PortalDefault:{2}<br/>WeatherLocale:{3}", Globalization.CultureInfo.CurrentCulture.ToString, UserInfo.Profile.PreferredLocale, PortalSettings.DefaultLanguage, w.WeatherLanguage))
            End If

            If Not DotNetNuke.Common.Globals.HostSettings("ProxyServer") Is Nothing Then w.ProxyServer = DotNetNuke.Common.Globals.HostSettings("ProxyServer").ToString()
            If Not DotNetNuke.Common.Globals.HostSettings("ProxyPort") Is Nothing AndAlso Microsoft.VisualBasic.IsNumeric(DotNetNuke.Common.Globals.HostSettings("ProxyPort").ToString()) Then w.ProxyPort = Integer.Parse(DotNetNuke.Common.Globals.HostSettings("ProxyPort").ToString())
            If Not DotNetNuke.Common.Globals.HostSettings("ProxyUsername") Is Nothing Then w.ProxyUsername = DotNetNuke.Common.Globals.HostSettings("ProxyUsername").ToString()
            If Not DotNetNuke.Common.Globals.HostSettings("ProxyPassword") Is Nothing Then w.ProxyPassword = DotNetNuke.Common.Globals.HostSettings("ProxyPassword").ToString()
            'Provide the Localization Class an Instance of the current datapath for the translation files
            If HttpContext.Current.Cache("w:Lang:Path") Is Nothing Then
                HttpContext.Current.Cache.Insert("w:Lang:Path", Me.ModulePath)
            End If
        End Sub

#End Region

    End Class

End Namespace
